using SqlSugar;
using Digitalmes.Domain.Repositories;

namespace Digitalmes.Infrastructure.Data;

/// <summary>
/// 工作单元管理者。
/// </summary>
internal sealed class UnitOfWorkManager(ISqlSugarClient sqlSugarClient) : IUnitOfWorkManage
{
    private SugarUnitOfWork? _unitOfWork;

    public IUnitOfWork CreateUow()
    {
        _unitOfWork = sqlSugarClient.CreateContext(sqlSugarClient.Ado.IsNoTran());
        return new UnitOfWork(_unitOfWork);
    }

    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    /// <remarks>注意：在同一事务中，获取的仓储对象进行数据操作时不能并行运行。</remarks>
    public IRepository<T> GetRepository<T>() where T : class, IEntity, new()
    {
        Guard.Against.Null(_unitOfWork, nameof(SugarUnitOfWork));

        //return new SqlSugarRepository<T>(_unitOfWork.Db); // 带作用域
        return new SqlSugarRepositoryWrapper<T>(_unitOfWork!.GetRepository<T>().Context); // 不带作用域
    }

    /// <summary>
    /// 仓储对象包装器。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    sealed class SqlSugarRepositoryWrapper<T>(ISqlSugarClient context) : SimpleClient<T>(context), IRepository<T>
        where T : class, IEntity, new()
    {
        public async Task<T?> GetByIdAsync(long id, CancellationToken cancellationToken = default)
        {
            return await base.GetByIdAsync(id, cancellationToken);
        }
    }
}
